package cn.intellijboy.gradle.plugin;

import cn.intellijboy.gradle.plugin.extension.GradleSettingExtension;
import org.gradle.api.Plugin;
import org.gradle.api.artifacts.repositories.MavenArtifactRepository;
import org.gradle.api.initialization.ProjectDescriptor;
import org.gradle.api.initialization.Settings;

/**
 * Spring AI Settings 约定插件：
 * - 统一配置 pluginManagement 中的插件版本
 * - 统一配置 pluginManagement 中的仓库镜像
 * - 提供标准化的插件管理配置
 */
public class GradleSettingsPlugin implements Plugin<Settings> {

    @Override
    public void apply(Settings settings) {
        // 创建/获取扩展并设置默认值
        GradleSettingExtension ext = settings.getExtensions()
            .create("springAi", GradleSettingExtension.class);
        setDefaultsIfAbsent(ext);

        // 配置插件仓库镜像
        configurePluginRepositories(settings, ext);

        // 在settings评估完成后执行
        settings.getGradle().settingsEvaluated(gradleSettings -> {
            // 配置构建文件名称
            modifyBuildFileNames(gradleSettings.getRootProject());
        });
    }

    /**
     * 递归设置构建配置文件名称
     * @param project 项目对象
     */
    private void modifyBuildFileNames(ProjectDescriptor project) {
        for (ProjectDescriptor child : project.getChildren()) {
            child.setBuildFileName(child.getName() + ".gradle.kts");
            modifyBuildFileNames(child);
        }
    }


    private void configurePluginRepositories(Settings settings, GradleSettingExtension ext) {
        // 本地仓库优先
        settings.getPluginManagement().getRepositories().mavenLocal();

        // 用户自定义顺序的插件仓库列表
        if (ext.getPluginRepositories() != null && ext.getPluginRepositories().isPresent()) {
            for (String url : ext.getPluginRepositories().get()) {
                if (url != null && !url.isEmpty()) {
                    settings.getPluginManagement().getRepositories().maven(repo -> {
                        configMavenRepo(repo, url, url);
                    });
                }
            }
        } else {
            // 默认镜像列表（国内优先）
            settings.getPluginManagement().getRepositories().maven(repo -> {
                configMavenRepo(repo, "Tencent Repository", "https://mirrors.cloud.tencent.com/gradle/");
            });
            settings.getPluginManagement().getRepositories().maven(repo -> {
                configMavenRepo(repo, "Alibaba Repository", "https://maven.aliyun.com/repository/gradle-plugin");
            });
            settings.getPluginManagement().getRepositories().maven(repo -> {
                configMavenRepo(repo, "Huawei Repository", "https://repo.huaweicloud.com/repository/maven/");
            });
        }

        // Gradle 插件门户
        settings.getPluginManagement().getRepositories().gradlePluginPortal();

        // Maven Central 作为备用
        settings.getPluginManagement().getRepositories().mavenCentral();
    }

    private void configMavenRepo(MavenArtifactRepository repo, String name, String url) {
        repo.setName(name);
        repo.setUrl(url);
    }

    private void setDefaultsIfAbsent(GradleSettingExtension ext) {
        if (ext.getPluginRepositories() != null && !ext.getPluginRepositories().isPresent()) {
            ext.getPluginRepositories().set(
                settingsDefaultPluginRepos()
            );
        }
    }

    private java.util.List<String> settingsDefaultPluginRepos() {
        java.util.List<String> list = new java.util.ArrayList<>();
        list.add("https://mirrors.cloud.tencent.com/gradle/");
        list.add("https://maven.aliyun.com/repository/gradle-plugin");
        list.add("https://repo.huaweicloud.com/repository/maven/");
        return list;
    }
}
